package com.example.demo.service.impl;

import com.example.demo.entity.MonitorcodeInfo;
import com.example.demo.entity.MonitorobjInfo;
import com.example.demo.service.TestAccessService;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Socket;

/**
 * 验证IP,端口是否可以联通的实现类
 * Created by tanjun on 2021-12-30.
 */
@Component
public class TestIpportAccessService extends BaseAccessService implements TestAccessService  {

    public static void main(String[] args) {
        TestIpportAccessService testservice=new TestIpportAccessService();
        testservice.testAccess("");
    }

    public void testAccess(String monitorObjId){
        //从数据库获取IP信息，端口信息
        MonitorobjInfo monitorobjInfo=monitorobjInfoMapper.selectByPrimaryKey(monitorObjId);
        if(monitorobjInfo.getMonitorobjCodeId()==null){
            return;
        }
        MonitorcodeInfo monitorcodeInfo=monitorcodeInfoMapper.selectByPrimaryKey(monitorobjInfo.getMonitorobjCodeId());
        Socket connect = new Socket();
        try {
            connect.connect(new InetSocketAddress(monitorcodeInfo.getIpAddress(), monitorcodeInfo.getNetport()),1000);
            boolean res = connect.isConnected();
            if(res){
                accessTestResultHandler.handlerAccessTestSuccess(monitorObjId,monitorcodeInfo.getMonitorcodeId());
            }else{
                accessTestResultHandler.handlerAccessTestfailure(monitorObjId,monitorcodeInfo.getMonitorcodeId());
            }

        } catch (IOException e) {
            e.printStackTrace();
            accessTestResultHandler.handlerAccessTestfailure(monitorObjId,monitorcodeInfo.getMonitorcodeId());
        }finally{
            try {
                connect.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
